package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.AboveTheQuotaApplyDao;
import com.wing.cabinet.dao.AboveTheQuotaApplyProductDao;
import com.wing.cabinet.dao.AuthorityManageDao;
import com.wing.cabinet.dao.AuthorityMemberDao;
import com.wing.cabinet.model.entity.AuthorityManage;
import com.wing.cabinet.model.entity.AuthorityMateriel;
import com.wing.cabinet.model.entity.AuthorityMember;
import com.wing.cabinet.model.entity.CountQuota;
import com.wing.cabinet.model.request.AuthorityMemberForm;
import com.wing.cabinet.model.response.AuthorityMemberVO;
import com.wing.cabinet.model.response.CellInventoryInoutVO;
import com.wing.common.exception.BusinessException;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 权限组成员表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class AuthorityMemberServiceImpl extends ServiceImpl<AuthorityMemberDao, AuthorityMember> implements AuthorityMemberService {

    @Autowired
    private CountQuotaService countQuotaService;

    @Autowired
    private AuthorityManageDao authorityManageDao;

    @Autowired
    private ReceiveRecordService receiveRecordService;
    @Autowired
    private AuthorityMaterielService authorityMaterielService;
    @Autowired
    private CellInventoryInoutService cellInventoryInoutService;
    @Autowired
    private AboveTheQuotaApplyProductDao aboveTheQuotaApplyProductDao;
    @Autowired
    private AboveTheQuotaApplyDao aboveTheQuotaApplyDao;

    private ExecutorService executorService= Executors.newFixedThreadPool(10);

    @Transactional
    @Override
    public int add(AuthorityMemberForm authorityMemberForm) {
        if(authorityMemberForm.getAuthorityManageId()==null) {
            return 0;
        }
        AuthorityManage authorityManage = authorityManageDao.selectById(authorityMemberForm.getAuthorityManageId());

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", authorityMemberForm.getUserId());
        List<AuthorityMember> tempList = baseMapper.selectList(queryWrapper);
        if(null != tempList && tempList.size()>0){
            throw new BusinessException("该用户已经存在于其他权限组");
        }
        //校验
        AuthorityMember authorityMember =new AuthorityMember();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(AuthorityMember.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(authorityMemberForm, authorityMember, copyOptions);

        Map<String, Object> parmas = new HashMap<String, Object>();
        if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
            parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
            parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
        }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
            parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
        }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
            parmas.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
        }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
            parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
        }
        parmas.put("endCreateTime",LocalDateTime.now());
        parmas.put("authorityManageId", authorityManage.getId());

        if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
            parmas.put("creator", authorityMember.getUserId());
            BigDecimal applyPrice = aboveTheQuotaApplyDao.getSumApplyPrice(parmas);
            BigDecimal applyQuantity = aboveTheQuotaApplyDao.getSumApplyQuantity(parmas);
            if(null == authorityManage.getCreditAmount()){
                authorityManage.setCreditAmount(new BigDecimal(0));
            }
            if(null == authorityManage.getCreditQuantity()){
                authorityManage.setCreditQuantity(0);
            }
            authorityMember.setPracticalCreditQuantity(authorityManage.getCreditQuantity() + applyQuantity.intValue());
            authorityMember.setPracticalLineOfCredit(authorityManage.getCreditAmount().add(applyPrice));

        }

        int result = baseMapper.insert(authorityMember);

        asyncAddCountQuota(authorityMember,authorityManage);

        return result;
    }

    @Transactional
    @Override
    public int addBatch(List<AuthorityMemberForm> authorityMemberFormList) {
        AuthorityManage authorityManage = authorityManageDao.selectById(authorityMemberFormList.get(0).getAuthorityManageId());
        if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)){//共享金额或者共享数量
            asyncAddCountQuotaShare(authorityMemberFormList,authorityManage);
        }
        int result = 0;
        for (AuthorityMemberForm authorityMemberForm:authorityMemberFormList){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", authorityMemberForm.getUserId());
            List<AuthorityMember> tempList = baseMapper.selectList(queryWrapper);
            if(null != tempList && tempList.size()>0){
                throw new BusinessException("该用户已经存在于其他权限组");
            }

            AuthorityMember authorityMember =new AuthorityMember();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(AuthorityMember.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(authorityMemberForm, authorityMember, copyOptions);
            authorityMember.setCreator(JwtUtils.getLoginUserId());
            authorityMember.setCreatorName(JwtUtils.getLoginUsername());

            Map<String, Object> parmas = new HashMap<String, Object>();
            if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                parmas.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
            }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
            }
            parmas.put("endCreateTime",LocalDateTime.now());
            parmas.put("authorityManageId", authorityManage.getId());

            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                parmas.put("creator", authorityMember.getUserId());
                BigDecimal applyPrice = aboveTheQuotaApplyDao.getSumApplyPrice(parmas);
                BigDecimal applyQuantity = aboveTheQuotaApplyDao.getSumApplyQuantity(parmas);
                if(null == authorityManage.getCreditAmount()){
                    authorityManage.setCreditAmount(new BigDecimal(0));
                }
                if(null == authorityManage.getCreditQuantity()){
                    authorityManage.setCreditQuantity(0);
                }
                authorityMember.setPracticalCreditQuantity(authorityManage.getCreditQuantity() + applyQuantity.intValue());
                authorityMember.setPracticalLineOfCredit(authorityManage.getCreditAmount().add(applyPrice));

            }

            baseMapper.insert(authorityMember);
            result++;
            if(authorityMemberForm.getAuthorityManageId()!=null){
                //AuthorityManage authorityManage = authorityManageDao.selectById(authorityMemberForm.getAuthorityManageId());
                if(!authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)&&!authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)){//不是共享金额或者共享数量
                    asyncAddCountQuota(authorityMember,authorityManage);
                }
            }
        }
        return result;
    }

    @Override
    public List<AuthorityMemberVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<AuthorityMemberVO> pageList4app(Page page, Map<String, Object> params) {
        List<AuthorityMemberVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public AuthorityMemberVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Transactional
    @Override
    public int deleteAuthorityMemberById(Long id) {
        AuthorityMember authorityMember = baseMapper.selectById(id);
        if(authorityMember == null){
            throw new BusinessException("删除失败");
        }
        int result = baseMapper.deleteById(id);
     /*   CountQuota countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                .eq(CountQuota::getAuthorityManageId, authorityMember.getAuthorityManageId())
                .eq(CountQuota::getReceiverId, authorityMember.getUserId()));
        if(countQuota!=null){
            countQuotaService.removeById(countQuota.getId());
        }*/
        List<CountQuota> list = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                .eq(CountQuota::getAuthorityManageId, authorityMember.getAuthorityManageId())
                .eq(CountQuota::getReceiverId, authorityMember.getUserId()));
        if(list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                countQuotaService.removeById(list.get(i).getId());
            }
        }
        return result;
    }

    @Transactional
    @Override
    public int batchDeleteAuthorityMemberById(Long[] ids) {
        if(ids!=null){
            for(Long item:ids){
                AuthorityMember authorityMember = baseMapper.selectById(item);
                if(authorityMember != null){
                    CountQuota countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                            .eq(CountQuota::getAuthorityManageId, authorityMember.getAuthorityManageId())
                            .eq(CountQuota::getReceiverId, authorityMember.getUserId()));
                    countQuotaService.removeById(countQuota.getId());
                }
            }
            return baseMapper.deleteBatchIds(Arrays.asList(ids));
        }
        return 0;
    }

    void asyncStatistical(AuthorityMember authorityMember, AuthorityManage authorityManage){
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            asyncAddCountQuota(authorityMember,authorityManage);
                        }catch (Exception e){
                            log.error("asyncAddCountQuota fail",e);
                        }

                    }
                });
            }
        });
    }

    void asyncAddCountQuota(AuthorityMember authorityMember, AuthorityManage authorityManage){
        List<AuthorityMateriel> list =  authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManage.getId()));

        //例如 10月10号创建权限组，周期为每月， 要查询该员工从10月01号到创建权限组时已经领了的金额或者数量，将金额或者数量算入已领取
        //可领金额或者数量的额度要减去已领取的
        Map<String,Object> param = new HashMap();
        param.put("type",2);
        param.put("creatorId",authorityMember.getUserId());
        param.put("endCreateTime",LocalDateTime.now());
        List<CellInventoryInoutVO> cellInventoryInoutVOList = null;
        //总数量
        Integer number = 0;
        //总金额
        BigDecimal amount = new BigDecimal(0);
        for (AuthorityMateriel authorityMateriel:list){
            CountQuota countQuota = new CountQuota();
            countQuota.setReceiverId(authorityMember.getUserId());
            countQuota.setReceiverName(authorityMember.getUserName());
            countQuota.setAuthorityManageId(authorityManage.getId());
            countQuota.setSkuCode(authorityMateriel.getSkuCode());
            param.put("skuCode4Detail",authorityMateriel.getSkuCode());
            //授信类型为金额
            if(authorityManage.getCreditType().getValue() == 0){
                countQuota.setCreditType(CountQuota.CreditType.money);
                // 授信额度
                BigDecimal usableAmount = authorityMateriel.getAmount();
                countQuota.setLineOfCredit(usableAmount);
                //授信方式
                if(authorityManage.getCreditWay().name().equals("independent")){//组员独立授信领用金额
                    countQuota.setCreditWay(CountQuota.CreditWay.independent);
                    if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.day);
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY)), LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.week);
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth()), LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.month);
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.of(LocalDate.now().plusMonths(3).getYear(),LocalDate.now().plusMonths(3).getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.quarter);
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextYear()), LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.year);
                    }
                    cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
                    if (cellInventoryInoutVOList.size()>0){
                        for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                            amount = amount.add(cellInventoryInoutVO.getTotal());
                        }
                    }
                    if(usableAmount.compareTo(amount)<0){//物料额度小于已经领取的
                        countQuota.setBalance(new BigDecimal(0));//剩余额度就为0
                    }else{//物料额度大于等于已经领取的
                        countQuota.setBalance(usableAmount.subtract(amount));//剩余额度就为物料额度减去已经领取的
                    }
                }else if(authorityManage.getCreditWay().name().equals("unlimited")){//不限制
                    countQuota.setCreditWay(CountQuota.CreditWay.unlimited);
                }
            }else if(authorityManage.getCreditType().getValue() == 1){
                countQuota.setCreditType(CountQuota.CreditType.quantity);
                // 授信数量
                Integer usableQuantity = authorityMateriel.getNumber();
                //授信数量
                countQuota.setAuthorizedQuantity(usableQuantity);
                //授信方式
                if(authorityManage.getCreditWay().name().equals("independentQuantity")){//组员独立授信领用数量
                    countQuota.setCreditWay(CountQuota.CreditWay.independentQuantity);
                    if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.day);
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY)), LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.week);
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth()), LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.month);
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.of(LocalDate.now().plusMonths(3).getYear(),LocalDate.now().plusMonths(3).getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.quarter);
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                        countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextYear()), LocalTime.MIN));
                        countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.year);
                    }
                    cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
                    if (cellInventoryInoutVOList.size()>0){
                        for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                            number = number+cellInventoryInoutVO.getQuantityPack();
                        }
                    }
                    if(usableQuantity-number<0){//物料数量小于已经领取的
                        countQuota.setResidualQuantity(0);//剩余数量就为0
                    }else{//物料数量大于等于已经领取的
                        countQuota.setResidualQuantity(usableQuantity-number);//剩余数量就为物料数量减去已经领取的
                    }
                }else if(authorityManage.getCreditWay().name().equals("unlimitedQuantity")){//不限制
                    countQuota.setCreditWay(CountQuota.CreditWay.unlimitedQuantity);
                }
            }
            countQuotaService.save(countQuota);
        }

    }

    //共享的
    void asyncAddCountQuotaShare(List<AuthorityMemberForm> authorityMemberFormList, AuthorityManage authorityManage){


        //例如 10月10号创建权限组，周期为每月， 要查询该员工从10月01号到创建权限组时已经领了的金额或者数量，将金额或者数量算入已领取
        //可领金额或者数量的额度要减去已领取的
        Map<String,Object> param = new HashMap();
        param.put("type",2);
        param.put("endCreateTime",LocalDateTime.now());
        //共享的 查一个组的
        List<CellInventoryInoutVO> cellInventoryInoutVOList = null;
        //总数量
        Integer number = 0;
        //总金额
        BigDecimal amount = new BigDecimal(0);

        //要看这个权限组是不是第一次添加成员 第一次则插入 不是则更新
        QueryWrapper<CountQuota> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("authority_manage_id",authorityManage.getId());
        List<CountQuota> listCount = countQuotaService.list(queryWrapper);
        if (listCount.size()>0){//不是第一次添加 更新
            for(CountQuota countQuota:listCount){
                param.put("skuCode4Detail",countQuota.getSkuCode());
                for(AuthorityMemberForm authorityMemberForm:authorityMemberFormList){//计算这个组的所有人已经领了的数据
                    param.put("creatorId",authorityMemberForm.getUserId());
                    if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                    }
                    cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
                    if (cellInventoryInoutVOList.size()>0){
                        for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                            amount = amount.add(cellInventoryInoutVO.getTotal());
                            number = number+cellInventoryInoutVO.getQuantityPack();
                        }
                    }
                }
                if(authorityManage.getCreditType().getValue() == 0){
                    // 授信额度
                    BigDecimal usableAmount = countQuota.getLineOfCredit();
                    if(usableAmount.compareTo(amount)<0){//物料额度小于已经领取的
                        countQuota.setBalance(new BigDecimal(0));//剩余额度就为0
                    }else{//物料额度大于等于已经领取的
                        countQuota.setBalance(usableAmount.subtract(amount));//剩余额度就为物料额度减去已经领取的
                    }
                }else if(authorityManage.getCreditType().getValue() == 1){
                    // 授信数量
                    Integer usableQuantity = countQuota.getAuthorizedQuantity();
                    if(usableQuantity-number<0){//物料数量小于已经领取的
                        countQuota.setResidualQuantity(0);//剩余数量就为0
                    }else{//物料数量大于等于已经领取的
                        countQuota.setResidualQuantity(usableQuantity-number);//剩余数量就为物料数量减去已经领取的
                    }
                }
                countQuotaService.updateById(countQuota);
            }
        }else{//第一次添加 插入  每个sku就一条数据 不是每个人每个sku一条数据
            List<AuthorityMateriel> list =  authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManage.getId()));
            for (AuthorityMateriel authorityMateriel:list){
                CountQuota countQuota = new CountQuota();
                countQuota.setAuthorityManageId(authorityManage.getId());
                countQuota.setSkuCode(authorityMateriel.getSkuCode());
                if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.day);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.week);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY)), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.month);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth()), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.quarter);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.of(LocalDate.now().plusMonths(3).getYear(),LocalDate.now().plusMonths(3).getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.year);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextYear()), LocalTime.MIN));
                }
                param.put("skuCode4Detail",authorityMateriel.getSkuCode());
                for(AuthorityMemberForm authorityMemberForm:authorityMemberFormList){//计算这个组的所有人已经领了的数据
                    param.put("creatorId",authorityMemberForm.getUserId());
                    if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                    }
                    cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
                    if (cellInventoryInoutVOList.size()>0){
                        for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                            amount = amount.add(cellInventoryInoutVO.getTotal());
                            number = number+cellInventoryInoutVO.getQuantityPack();
                        }
                    }
                }
                if(authorityManage.getCreditType().getValue() == 0){
                    countQuota.setCreditType(CountQuota.CreditType.money);
                    // 授信额度
                    BigDecimal usableAmount = authorityMateriel.getAmount();
                    countQuota.setLineOfCredit(usableAmount);
                    if(authorityManage.getCreditWay().name().equals("share")){//组员共享领用金额
                        countQuota.setCreditWay(CountQuota.CreditWay.share);
                    }
                    if(usableAmount.compareTo(amount)<0){//物料额度小于已经领取的
                        countQuota.setBalance(new BigDecimal(0));//剩余额度就为0
                    }else{//物料额度大于等于已经领取的
                        countQuota.setBalance(usableAmount.subtract(amount));//剩余额度就为物料额度减去已经领取的
                    }
                }else if(authorityManage.getCreditType().getValue() == 1){
                    countQuota.setCreditType(CountQuota.CreditType.quantity);
                    // 授信数量
                    Integer usableQuantity = authorityMateriel.getNumber();
                    //授信数量
                    countQuota.setAuthorizedQuantity(usableQuantity);
                    //授信方式
                    if(authorityManage.getCreditWay().name().equals("shareQuantity")) {//组员共享领用数量
                        countQuota.setCreditWay(CountQuota.CreditWay.shareQuantity);
                    }
                    if(usableQuantity-number<0){//物料数量小于已经领取的
                        countQuota.setResidualQuantity(0);//剩余数量就为0
                    }else{//物料数量大于等于已经领取的
                        countQuota.setResidualQuantity(usableQuantity-number);//剩余数量就为物料数量减去已经领取的
                    }
                }
                countQuotaService.save(countQuota);
            }
        }
    }
}
